package cn.web.demo.security;

import cn.web.demo.DemoApplication;
import cn.web.demo.model.Permission;
import cn.web.demo.service.IPermissionService;
import cn.web.demo.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Configuration
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      cn.web.demo.model.User user=  userService.findByUsername(username);
      if(user ==null){
          return null;
      }
      String pwd=passwordEncoder.encode(user.getPassword());
      List<Permission> permissionList=permissionService.findPermissionListByUserId(user.getId());
        return new User(username
                ,pwd
                ,getAuthorities(permissionList)
        );
    }

    public Collection<GrantedAuthority> getAuthorities(List<Permission> permissions) {
        List<GrantedAuthority> list=new ArrayList<>();
        if(permissions == null){return list;}
        for(Permission permission:permissions){
            if(!StringUtils.isEmpty(permission.getPath())){
                list.add(new SimpleGrantedAuthority(permission.getAuthorization_flag()));
            }
        }
        return list;
    }
}
